﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;

namespace Freedom.Framework.Mvc.Controller
{
    public class FreedomControllerFactory: DefaultControllerFactory 
    {
        private readonly IContainer _container;

        public FreedomControllerFactory(IContainer container)
        {
            _container = container;
        }

        protected override Type GetControllerType(RequestContext requestContext, string controllerName)
        {
            var area = Utils.GetAreaName(requestContext.RouteData);
            var key = string.Format("{0}.Controllers.{1}Controller", area, controllerName).ToLower();
            try
            {
                var controllerDic = _container.ResolveKeyed<Dictionary<string, Type>>("ControllerDic");
                if(controllerDic.ContainsKey(key))
                {
                    return controllerDic[key];
                }
                return base.GetControllerType(requestContext, controllerName);
            }
            catch (Exception)
            {
                return base.GetControllerType(requestContext, controllerName);
            }
        }
    }
}
